﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MyCommerce.ManagementBase.Common.Base.Common;
using Innova.Microfinanzas.BusinessEntities;
using Innova.Microfinanzas.BusinessEntities.SystemEnums;
using MyCommerce.Business.GeneralParameters;
using System.IO;
using System.Text.RegularExpressions;
using Innova.Microfinanzas.Windows.Common.Views;
using MyCommerce.Windows.Reports.Reportes;
using CrystalDecisions.CrystalReports.Engine;
using Innova.Microfinanzas.BusinessEntities.EnumClassifierTypes;
//using MyCommerce.Presentation.Reports.Reports.Stores;

namespace MyCommerce.Windows.Reports.Views
{
    public partial class StoresReportView : BaseForm
    {
        private ReportType loadReportType = ReportType.Conveyors;

        public StoresReportView()
        {
            InitializeComponent();
        }

        private void PrintReport(bool print)
        {
            DataTable dtResult = new DataTable();
            object reportType = null;
            switch (loadReportType)
            {
                case ReportType.Stores:
                    dtResult = ReportManager.GetStoreReport();
                    StoreReport vStoreReport = new StoreReport();
                    reportType = (Object)vStoreReport;
                    dtResult.TableName = "StoreReport";
                    break;
                case ReportType.DealerStores:
                    dtResult = ReportManager.GetDealerStoreReport();
                    DealerStoreReport vDealerStoreReport = new DealerStoreReport();
                    reportType = (Object)vDealerStoreReport;
                    dtResult.TableName = "DealerStoreReport";
                    break;
                case ReportType.Suppliers:
                    dtResult = ReportManager.GetSupplierReport(treeCountries.GetSelectedEntitiesIdList());
                    SuppliesReport vSuppliesReport = new SuppliesReport();
                    reportType = (Object)vSuppliesReport;
                    dtResult.TableName = "SuppliesReport";
                    break;
                case ReportType.Conveyors:
                    dtResult = ReportManager.GetConveyorReport();
                    ConveyorsReport vConveyorsReport = new ConveyorsReport();
                    reportType = (Object)vConveyorsReport;
                    dtResult.TableName = "ConveyorsReport";
                    break;
                case ReportType.Products:
                    dtResult = ReportManager.GetProductReport(treeMark.GetSelectedEntitiesIdList());
                    ProductsReport vProductsReport = new ProductsReport();
                    reportType = (Object)vProductsReport;
                    dtResult.TableName = "ProductsReport";
                    break;
                case ReportType.ProductPrices:
                    dtResult = ReportManager.GetProductPriceReport(treeMark.GetSelectedEntitiesIdList());
                    ProductPricesReport vProductPricesReport = new ProductPricesReport();
                    reportType = (Object)vProductPricesReport;
                    dtResult.TableName = "ProductPricesReport";
                    break;
                //case ReportType.StoreStock:
                //    dtResult = ReportManager.GetDealerStoreReport();
                //    //reportType = typeof(StoreStockReport);
                //    dtResult.TableName = "StoreStockReport";
                //    break;
                //case ReportType.Sales:
                //    dtResult = ReportManager.GetDealerStoreReport();
                //    //reportType = typeof(SalesReport);
                //    dtResult.TableName = "SalesReport";
                //    break;
                //case ReportType.InOutCashFlow:
                //    dtResult = ReportManager.GetDealerStoreReport();
                //    //reportType = typeof(InOutCashFlowReport);
                //    dtResult.TableName = "InOutCashFlowReport";
                //    break;
                default:
                    break;
            }
            if (print)
            {
                ReportViewer viewerRpt = new ReportViewer(reportType, dtResult);
                viewerRpt.ShowDialog();
            }
            else
                SchemaHelper.GenerateSchema(dtResult);
        }

        private void StoresReportView_Load(object sender, EventArgs e)
        {
            switch (this.Context.ObjCommandLoad.CommandKey)
            {
                case "reportStore":
                    loadReportType = ReportType.Stores;
                    break;
                case "reportDealerStore":
                    loadReportType = ReportType.DealerStores;
                    break;
                case "reportConveyors":
                    loadReportType = ReportType.Conveyors;
                    break;
                case "reportSuppliers":
                    loadReportType = ReportType.Suppliers;
                    LoadTreeCountries();
                    break;
                case "reportProducts":
                    loadReportType = ReportType.Products;
                    LoadTreeMark();
                    break;
                case "reportProductPrice":
                    loadReportType = ReportType.ProductPrices;
                    LoadTreeMark();
                    break;
                default:
                    break;
            }            
        }

        private void tsCloseButtonToolStrip_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void tsPrintButtonToolStrip_Click(object sender, EventArgs e)
        {
            PrintReport(true);
        }

        private void btnGenerar_Click(object sender, EventArgs e)
        {
            PrintReport(false);
        }

        private void LoadTreeCountries()
        {
            panelCountries.Visible = true;
            CountryManager vCountryManager = new CountryManager();
            treeCountries.SetNodes<Country>(vCountryManager.GetListCountries(), "NameCountry", "IdCountry");
            treeCountries.Show();
        }

        private void LoadTreeMark()
        {
            panelMark.Visible = true;
            CommonClassifierManager vCommonClassifierManager = new CommonClassifierManager();
            treeMark.SetNodes<Classifier>(vCommonClassifierManager.GetClassifierByIDType((long)CommonClassifierTypes.ProductMark), "Name", "IdClassifier");
            treeMark.Show();
        }
    }

    /// <summary>
    /// clase q genera esquemas
    /// </summary>
    public static class SchemaHelper
    {
        private static void Generate(DataTable data, string schemaPath)
        {
            data.WriteXmlSchema(schemaPath);
            StreamReader schema = File.OpenText(schemaPath);
            string input = schema.ReadToEnd();
            schema.Close();
            File.Delete(schemaPath);
            Match m = Regex.Match(input, "msdata:MainDataTable=(.*$)", RegexOptions.Multiline);
            string dataTableName = m.Groups[1].ToString().Split(' ')[0].Replace("\"", "");

            if (!string.IsNullOrEmpty(data.TableName))
                input = input.Replace(dataTableName, data.TableName);
            else
                input = input.Replace(dataTableName, "Sin-Nombre");

            StreamWriter schemaWriter = new StreamWriter(schemaPath);
            schemaWriter.Write(input);
            schemaWriter.Flush();
            schemaWriter.Close();
        }

        /// <summary>
        /// genera el esquema de un DataTable dado
        /// y devuelve el nombrew del archivo generado
        /// </summary>
        /// <param name="data">tabla a generar</param>
        public static string GenerateSchema(DataTable data)
        {
            SaveFileDialog vFile = new SaveFileDialog();
            vFile.Filter = "*.xsd|*.xsd";
            vFile.FileName = data.TableName;
            if (vFile.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    Generate(data, vFile.FileName);
                    MessageBox.Show("El esquema fue generado correctamente", "Esquema");
                    return vFile.FileName;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: \n" + ex.Message, "Esquema");
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// genera el esquema de un DataTable dado
        /// y devuelve el nombrew del archivo generado
        /// </summary>
        /// <param name="data">tabla a generar</param>
        public static string GenerateSchema(DataSet data)
        {
            StringBuilder vResult = new StringBuilder();
            foreach (DataTable vTable in data.Tables)
            {
                vResult.AppendLine(GenerateSchema(vTable));
            }
            return vResult.ToString();
        }

        /// <summary>
        /// genera el esquema de un DataTable dado
        /// y devuelve el nombrew del archivo generado
        /// </summary>
        /// <param name="data">tabla a generar</param>
        public static string GenerateSchema(IList<DataTable> data)
        {
            StringBuilder vResult = new StringBuilder();
            foreach (DataTable vTable in data)
            {
                vResult.AppendLine(GenerateSchema(vTable));
            }
            return vResult.ToString();
        }
    }
}
